package com.Cychat.pet.utils;

import com.Cychat.commons.config.OssConfig;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ObjectMetadata;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Component
public class OSSUtil {

    @Autowired
    private OSS ossClient;
    
    @Autowired
    private OssConfig ossConfig;

    // 图片上传路径前缀
    private static final String IMAGE_PREFIX = "pet/images/";
    
    // 支持的图片类型
    private static final String[] ALLOWED_IMAGE_TYPES = {
        "image/jpeg", "image/png", "image/gif", "image/bmp","image/jpg"
    };

    /**
     * 上传图片到OSS
     */
    public String uploadImage(MultipartFile file) throws Exception {
        // 校验文件
        validateFile(file);
        
        // 生成文件名：时间戳+UUID+原文件后缀
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = new SimpleDateFormat("yyyyMMdd/").format(new Date()) + 
                         UUID.randomUUID().toString() + suffix;
        
        // 构建OSS存储路径
        String key = IMAGE_PREFIX + fileName;
        
        // 上传文件
        try (InputStream inputStream = file.getInputStream()) {
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(file.getContentType());
            metadata.setContentLength(file.getSize());
            
            ossClient.putObject(ossConfig.getBucketName(), key, inputStream, metadata);
        }
        
        // 返回完整访问URL
        return "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + key;
    }

    /**
     * 校验文件合法性
     */
    private void validateFile(MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new Exception("上传文件不能为空");
        }
        
        // 校验文件类型
        String contentType = file.getContentType();
        boolean isAllowed = false;
        for (String type : ALLOWED_IMAGE_TYPES) {
            if (type.equals(contentType)) {
                isAllowed = true;
                break;
            }
        }
        if (!isAllowed) {
            throw new Exception("不支持的文件类型，仅支持JPG、PNG、GIF、BMP格式");
        }
        
        // 校验文件大小（限制10MB）
        if (file.getSize() > 10 * 1024 * 1024) {
            throw new Exception("文件大小不能超过10MB");
        }
    }
}